// 用户相关API接口
import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: '/api', // 后端API基础路径
  timeout: 10000,
  withCredentials: true // 支持session
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    console.error('API请求错误:', error)
    // 如果后端返回了错误响应，提取错误信息
    if (error.response && error.response.data) {
      return Promise.reject(error.response.data)
    }
    return Promise.reject(error)
  }
)

// 用户接口类型定义
export interface User {
  id?: number
  username: string
  password: string
  email?: string
  role?: string
  roles?: string
}

export interface LoginRequest {
  username: string
  password: string
  roles: string
}

export interface RegisterRequest {
  username: string
  password: string
  email: string
  role: string
}

export interface UpdatePasswordRequest {
  oldPassword: string
  newPassword: string
}

// 更新ApiResponse接口定义
export interface ApiResponse<T = any> {
  code: number
  message?: string
  msg?: T  // 确保 msg 字段是泛型 T 类型
  data?: any  // data字段通常是状态消息
  // 直接包含分页数据的字段
  list?: any[]
  total?: number
  pageNum?: number
  pageSize?: number
}

// 用户API接口
// 在现有的接口类型定义后添加订单相关类型
export interface DeliveryOrderRequest {
  // 寄件人信息
  senderName: string
  senderPhone: string
  senderAddress: string
  
  // 收件人信息
  receiverName: string
  receiverPhone: string
  receiverAddress: string
  
  // 物品信息
  itemWeight: number  // 改为 number 类型
  itemVolume: number  // 改为 number 类型
  itemType: string    // 改为 string 类型
  insuredValue: number
  
  // 费用信息
  baseFee: number
  weightFee: number
  serviceFee: number
  insuranceFee: number
  totalFee: number
  
  // 配送信息
  remark: string
  paymentMethod: string
}

// 在userApi对象中添加订单创建方法
// 订单相关接口类型定义
export interface DeliveryOrder {
  deliveryOrderId: number
  orderNumber: string
  userId: number
  senderName: string
  senderPhone: string
  senderAddress: string
  receiverName: string
  receiverPhone: string
  receiverAddress: string
  itemVolume: number
  itemWeight: number
  itemType: string
  insuredValue: number
  baseFee: number
  weightFee: number
  serviceFee: number
  insuranceFee: number
  totalFee: number
  remark: string
  delivererId?: number
  paymentMethod: string
  orderStatus: number
  createdAt: string
  updatedAt: string
}

export interface OrderListResponse {
  list: DeliveryOrder[]
  total: number
  pageNum: number
  pageSize: number
}

// 在userApi对象中添加搜索订单方法
// 在现有接口类型定义后添加地址相关类型
export interface Address {
  addressId?: number     // 地址ID
  userId?: number        // 用户ID
  contactName: string    // 联系人姓名
  contactPhone: string   // 联系人电话
  fullAddress: string    // 完整地址
  longitude?: number     // 经度
  latitude?: number      // 纬度
  geocodeStatus?: number // 地理编码状态
  geocoded?: boolean     // 是否已地理编码
  isDefault: number      // 1-寄件地址，0-收件地址
  createdAt?: string     // 创建时间
  updatedAt?: string     // 更新时间
}

export interface CreateAddressRequest {
  contactName: string
  contactPhone: string
  fullAddress: string
  isDefault: number
}

export interface AddressListResponse {
  list: Address[]
  total: number
  pageNum: number
  pageSize: number
}

// 在现有接口类型定义后添加物流轨迹相关类型
// 物流轨迹相关类型定义
export interface TrackRecord {
  timestamp: string
  status: number
  description: string
  location: {
    longitude: number
    latitude: number
    address: string
  }
  operator: string | null
  remark: string | null
}

// 物流轨迹
export interface DeliveryTrack {
  id: string
  deliveryOrderId: number
  orderNumber: string
  trackRecords: TrackRecord[]
  createdAt: string
  updatedAt: string
}
// 在现有的物流轨迹相关类型定义后添加新的类型
export interface CompleteTrackInfo {
  order: {
    deliveryOrderId: number
    orderNumber: string
    userId: number
    senderName: string
    senderPhone: string
    senderAddress: string
    receiverName: string
    receiverPhone: string
    receiverAddress: string
    itemVolume: number
    itemWeight: number
    itemType: string
    insuredValue: number
    baseFee: number
    weightFee: number
    serviceFee: number
    insuranceFee: number
    totalFee: number
    remark: string
    delivererId: number | null
    paymentMethod: string
    orderStatus: number
    createdAt: string
    updatedAt: string | null
  }
  track: {
    id: string
    deliveryOrderId: number
    orderNumber: string
    trackRecords: TrackRecord[]
    createdAt: string
    updatedAt: string
  }
}

// 获取常用地址接口类型定义
export interface FrequentAddress {
  address: string
  phone: string
  name: string
  totalWeight: number
}

export interface FrequentAddressResponse {
  msg: string
  code: number
  data: FrequentAddress[]
}

// 在 userApi 对象中添加方法
export const userApi = {
  // 用户注册
  register(userData: RegisterRequest): Promise<ApiResponse> {
    // 将role字段映射为roles字段以匹配后端期望
    const requestData = {
      username: userData.username,
      password: userData.password,
      email: userData.email,
      roles: userData.role // 将role映射为roles
    }
    return api.post('/users/register', requestData)
  },

  // 用户登录
  // 如果后端期望JSON格式，修改login方法
  login(loginData: LoginRequest): Promise<ApiResponse> {
    const formData = new FormData()
    formData.append('username', loginData.username)
    formData.append('password', loginData.password)
    formData.append('roles', loginData.roles)
    
    return api.post('/users/login', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },

  // 获取用户信息
  getUserInfo(): Promise<ApiResponse> {
    return api.get('/users/getUser')
  },

  // 用户注销
  logout(): Promise<ApiResponse> {
    return api.post('/users/logout')
  },

  // 删除用户
  deleteUser(): Promise<ApiResponse> {
    return api.post('/users/deleteUser')
  },

  // 修改密码
  updatePassword(passwordData: UpdatePasswordRequest): Promise<ApiResponse> {
    const formData = new FormData()
    formData.append('oldPassword', passwordData.oldPassword)
    formData.append('newPassword', passwordData.newPassword)
    
    return api.post('/users/updatePassword', formData, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
  }, // 这里需要添加逗号
  
  // 创建订单
  createDeliveryOrder(orderData: DeliveryOrderRequest): Promise<ApiResponse> {
    return api.post('/deliveryOrders/createDeliveryOrder', orderData)
  },
  
  // 获取个人订单列表
  getDeliveryOrderList(pageNum: number = 1, pageSize: number = 3): Promise<ApiResponse<OrderListResponse>> {
    const formData = new FormData()
    formData.append('pageNum', pageNum.toString())
    formData.append('pageSize', pageSize.toString())
    
    return api.post('/deliveryOrders/getDeliveryOrderList', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },
  
  // 获取订单详情
  getDeliveryOrderDetail(deliveryOrderId: number): Promise<ApiResponse<DeliveryOrder>> {
    const formData = new FormData()
    formData.append('deliveryOrderId', deliveryOrderId.toString())
    
    return api.post('/deliveryOrders/getDeliveryOrderDetail', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },
  
  // 删除订单
  deleteDeliveryOrder(deliveryOrderId: number): Promise<ApiResponse> {
    const formData = new FormData()
    formData.append('deliveryOrderId', deliveryOrderId.toString())
    
    return api.post('/deliveryOrders/deleteDeliveryOrder', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },
  
  // 更新订单状态为已签收
  setDeliverying(deliveryOrderId: number): Promise<ApiResponse> {
    const formData = new FormData()
    formData.append('deliveryOrderId', deliveryOrderId.toString())
    
    return api.post('/deliveryOrders/setDeliverying', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  }
  ,
  // 搜索订单列表
  // 更新搜索订单列表接口，匹配后端参数
  selectDeliveryOrderList(
    orderNumber: string = '', 
    senderName: string = '', 
    receiverName: string = '', 
    pageNum: number = 1, 
    pageSize: number = 10
  ): Promise<ApiResponse<OrderListResponse>> {
    const formData = new FormData()
    formData.append('orderNumber', orderNumber)
    formData.append('senderName', senderName)
    formData.append('receiverName', receiverName)
    formData.append('pageNum', pageNum.toString())
    formData.append('pageSize', pageSize.toString())
    
    return api.post('/deliveryOrders/selectDeliveryOrderList', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },
  
  // 创建地址
  createAddress(addressData: CreateAddressRequest): Promise<ApiResponse> {
    return api.post('/address/create', addressData)
  },
  
  // 查询所有寄件地址
  queryAllSendAddress(pageNum: number = 1, pageSize: number = 5): Promise<ApiResponse> {
    return api.get('/address/queryAllSend', {
      params: {
        pageNum,
        pageSize
      }
    })
  },
  
  // 查询所有收件地址
  queryAllReceiveAddress(pageNum: number = 1, pageSize: number = 5): Promise<ApiResponse> {
    return api.get('/address/queryAllReceive', {
      params: {
        pageNum,
        pageSize
      }
    })
  }
  ,
  // 删除地址
  deleteAddress(addressId: number): Promise<ApiResponse> {
    const formData = new FormData()
    formData.append('addressId', addressId.toString())
    
    return api.post('/address/delete', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },
  
  // 修改地址
  updateAddress(addressData: Address): Promise<ApiResponse> {
    return api.post('/address/update', addressData)
  },
  
  // 获取订单状态分类列表,1-待发货
  getDeliveryStatusList(pageNum: number = 1, pageSize: number = 10): Promise<ApiResponse<OrderListResponse>> {
    const formData = new FormData()
    formData.append('pageNum', pageNum.toString())
    formData.append('pageSize', pageSize.toString())
    
    return api.post('/deliveryOrders/getDeliveryStatusList', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },
  
  // 获取订单状态分类列表,2-运输中
  getDeliveryProcessingList(pageNum: number = 1, pageSize: number = 10): Promise<ApiResponse<OrderListResponse>> {
    const formData = new FormData()
    formData.append('pageNum', pageNum.toString())
    formData.append('pageSize', pageSize.toString())
    
    return api.post('/deliveryOrders/getDeliveryProcessingList', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },
  
  // 获取订单状态分类列表,3-待签收
  getDeliveryDeliveryingList(pageNum: number = 1, pageSize: number = 10): Promise<ApiResponse<OrderListResponse>> {
    const formData = new FormData()
    formData.append('pageNum', pageNum.toString())
    formData.append('pageSize', pageSize.toString())
    
    return api.post('/deliveryOrders/getDeliveryDeliveryingList', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },
  
  // 获取订单状态分类列表,4-已完成
  getDeliveryCompletedList(pageNum: number = 1, pageSize: number = 10): Promise<ApiResponse<OrderListResponse>> {
    const formData = new FormData()
    formData.append('pageNum', pageNum.toString())
    formData.append('pageSize', pageSize.toString())
    
    return api.post('/deliveryOrders/getDeliveryCompletedList', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },



  getCompleteTrackInfo(orderNumber: string): Promise<ApiResponse<CompleteTrackInfo>> {
    return api.get('/deliveryTrack/getCompleteInfo', {
      params: {
        orderNumber
      }
    })
  },
  // 根据订单ID查询轨迹
  getTrackByOrderId(deliveryOrderId: number): Promise<ApiResponse> {
    const formData = new FormData()
    formData.append('deliveryOrderId', deliveryOrderId.toString())
    
    return api.post('/deliveryTrack/getByOrderId', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },
  // 获取订单统计信息
  getOrderStats(): Promise<ApiResponse<{
    total: number
    pending: number
    processing: number
    completed: number
    deliverying: number
  }>> {
    return api.get('/deliveryOrders/getDeliveryOrderCount')
  },
  // 获取订单最新信息
  getDeliveryOrderCount(pageNum: number = 1, pageSize: number = 4): Promise<ApiResponse<{
    total: number
    pageSize: number
    pageNum: number
    list: Array<{
      deliveryOrderId: number
      orderNumber: string
      userId: number
      senderName: string
      senderPhone: string
      senderAddress: string
      receiverName: string
      receiverPhone: string
      receiverAddress: string
      itemVolume: number
      itemWeight: number
      itemType: string
      insuredValue: number
      baseFee: number
      weightFee: number
      serviceFee: number
      insuranceFee: number
      totalFee: number
      remark: string
      delivererId: number | null
      paymentMethod: string
      orderStatus: number
      createdAt: string
      updatedAt: string | null
    }>
  }>> {
    return api.post('/deliveryOrders/getDeliveryOrderList', {
      params: {
        pageNum,
        pageSize
      }
    })
  },
    // 获取常用地址
    getFrequentAddresses(): Promise<FrequentAddressResponse> {
      return api.get('/address/frequent')
    },
  
} 
